package com.yuanjin.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.yuanjin.R;
import com.yuanjin.models.Map_MyLocation;
import com.yuanjin.models.Map_Petrol;
import com.yuanjin.models.Map_Station;
import com.yuanjin.util.Map_MyStationDB;
import com.yuanjin.util.Map_StationData;
import com.yuanjin.util.MyTimeUtils;

public class Map_MainActivity extends Activity implements OnClickListener {

	private Context mContext;
	private MapView mMapView = null;
	private BaiduMap mBaiduMap = null;
	private LocationClient mLocationClient = null;
	private BDLocationListener mListener = new MyLocationListener();

	private ImageView iv_list, iv_loc;
	private Toast mToast;
	private TextView tv_title_right, tv_name, tv_distance, tv_price_a,
			tv_price_b;
	private LinearLayout ll_summary;
	private Dialog selectDialog, loadingDialog;
	private Map_StationData stationData;
	private BDLocation loc;

	private ArrayList<Map_Station> mList;
	private Map_Station mStation = null;

	private int mDistance = 3000;
	private Marker lastMarker = null;

	/**************** 地图轨迹****me *******************/
	private boolean refreshing = true;
	private int time = 1;
	private Map_MyStationDB myDB;
	private SQLiteDatabase dbWriter;
	private SQLiteDatabase dbReader;
	private ArrayList<Map_MyLocation> mylocList;
	private Map_MyLocation myLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_activity_main);
		mContext = this;
		stationData = new Map_StationData(this, mHandler);
		initView();
	}

	private void initView() {
		iv_list = (ImageView) findViewById(R.id.iv_list);
		iv_list.setOnClickListener(this);
		iv_loc = (ImageView) findViewById(R.id.iv_loc);
		iv_loc.setOnClickListener(this);
		tv_title_right = (TextView) findViewById(R.id.tv_title_button);
		tv_title_right.setText("3km" + " >");
		tv_title_right.setVisibility(View.VISIBLE);
		tv_title_right.setOnClickListener(this);

		ll_summary = (LinearLayout) findViewById(R.id.ll_summary);
		ll_summary.setOnClickListener(this);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_distance = (TextView) findViewById(R.id.tv_distance);
		tv_price_a = (TextView) findViewById(R.id.tv_price_a);
		tv_price_b = (TextView) findViewById(R.id.tv_price_b);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.showScaleControl(false);
		mMapView.showZoomControls(false);
		mBaiduMap = mMapView.getMap();

		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
		mBaiduMap.setMyLocationEnabled(true);

		mLocationClient = new LocationClient(mContext);
		mLocationClient.registerLocationListener(mListener);

		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Battery_Saving);// 高精度Hight_Accuracy;
															// Battery_Saving:低精度.
		option.setCoorType("bd09ll"); // 返回国测局经纬度坐标系：gcj02 返回百度墨卡托坐标系 ：bd09
										// 返回百度经纬度坐标系 ：bd09ll
		option.setScanSpan(0);// 设置扫描间隔，单位毫秒，当<1000(1s)时，定时定位无效
		option.setIsNeedAddress(true);// 设置是否需要地址信息，默认为无地址
		option.setNeedDeviceDirect(true);// 在网络定位时，是否需要设备方向
		mLocationClient.setLocOption(option);

		/****************************** me *********************************/
		myDB = new Map_MyStationDB(this);
		dbWriter = myDB.getWritableDatabase();
		dbReader = myDB.getReadableDatabase();
		mylocList = new ArrayList<Map_MyLocation>();
		myLocation = new Map_MyLocation();
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				/********************** me *****************/
				while (refreshing) {
					try {
						Thread.sleep(20000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (mHandler != null) {
						Message msg = new Message();
						msg.what = 0x03;
						mHandler.sendMessage(msg);
					}

				}
			}
		});
		thread.start();

	}

	public void setMarker(ArrayList<Map_Station> list) {
		Log.e("setMarker", "进入setMarker");
		View view = LayoutInflater.from(mContext)
				.inflate(R.layout.marker, null);
		final TextView tv = (TextView) view.findViewById(R.id.tv_marker);
		for (int i = 0; i < list.size(); i++) {
			Map_Station s = list.get(i);
			tv.setText((i + 1) + "");
			if (i == 0) {
				tv.setBackgroundResource(R.drawable.icon_focus_mark);
			} else {
				tv.setBackgroundResource(R.drawable.icon_mark);
			}
			BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(tv);
			LatLng latLng = new LatLng(s.getLat(), s.getLon());
			Bundle b = new Bundle();
			b.putParcelable("s", list.get(i));
			OverlayOptions oo = new MarkerOptions().position(latLng)
					.icon(bitmap).title((i + 1) + "").extraInfo(b);
			if (i == 0) {
				lastMarker = (Marker) mBaiduMap.addOverlay(oo);
				mStation = s;
				// 将第一家加油站的信息显示在底部
				showLayoutInfo((i + 1) + "", mStation);
			} else {
				mBaiduMap.addOverlay(oo);
			}
		}
		// 图层的点击监听事件
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {
				// 把原已被点击点恢复
				if (lastMarker != null) {
					tv.setText(lastMarker.getTitle());
					tv.setBackgroundResource(R.drawable.icon_mark);
					BitmapDescriptor bitmap = BitmapDescriptorFactory
							.fromView(tv);
					lastMarker.setIcon(bitmap);
				}
				// 重新突出显示现被点击点
				lastMarker = marker;
				String position = marker.getTitle();
				tv.setText(position);
				tv.setBackgroundResource(R.drawable.icon_focus_mark);
				BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(tv);
				marker.setIcon(bitmap);
				mStation = marker.getExtraInfo().getParcelable("s");
				showLayoutInfo(position, mStation);
				return false;
			}
		});

	}

	public void setMarker2(ArrayList<Map_MyLocation> list) {
		Log.e("setMarker", "进入setMarker");
		View view = LayoutInflater.from(mContext)
				.inflate(R.layout.marker, null);
		final TextView tv = (TextView) view.findViewById(R.id.tv_marker);
		for (int i = 0; i < list.size(); i++) {
			Map_MyLocation s = list.get(i);
			tv.setText((i + 1) + "");
			if (i == 0) {
				tv.setBackgroundResource(R.drawable.icon_st);
				tv.setText("");
			} else if (i == list.size() - 1) {
				tv.setBackgroundResource(R.drawable.icon_en);
				tv.setText("");
			} else {
				tv.setBackgroundResource(R.drawable.icon_line_mark);
			}
			BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(tv);
			LatLng latLng = new LatLng(s.getLat(), s.getLon());
			Bundle b = new Bundle();
			b.putParcelable("s", list.get(i));
			OverlayOptions oo = new MarkerOptions().position(latLng)
					.icon(bitmap).title((i + 1) + "").extraInfo(b);
			if (i == list.size() - 1) {
				lastMarker = (Marker) mBaiduMap.addOverlay(oo);
				myLocation = s;
				// 将终点的信息显示在底部
				showLayoutInfo2((i + 1) + "", myLocation);
			} else {
				mBaiduMap.addOverlay(oo);
			}
		}

	}

	Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0x01:
				// mList = (ArrayList<Station>) msg.obj;
				// setMarker(mList);
				loadingDialog.dismiss();
				break;
			case 0x02:
				loadingDialog.dismiss();
				showToast(String.valueOf(msg.obj));
				break;
			case 0x03:
				int r = mLocationClient.requestLocation();
				switch (r) {
				case 1:
					showToast("服务没有启动。");
					break;
				case 2:
					showToast("没有监听函数。");
					break;
				case 6:
					showToast("请求间隔过短。");
					break;

				default:
					break;
				}
				Log.e("test", "第" + time + "次刷新");
				time++;
				break;
			default:
				break;
			}

		}

	};

	/**
	 * 地图下方的显示信息框数据显示
	 * 
	 * @param position
	 * @param s
	 */
	public void showLayoutInfo(String position, Map_Station s) {
		tv_name.setText(position + "." + s.getName());
		tv_distance.setText(s.getDistance() + "");
		List<Map_Petrol> list = s.getGastPriceList();

		if (list != null && list.size() > 0) {
			tv_price_a.setText(list.get(0).getType() + " "
					+ list.get(0).getPrice());
			if (list.size() > 1) {
				tv_price_b.setText(list.get(1).getType() + " "
						+ list.get(1).getPrice());
			}
		}
		ll_summary.setVisibility(View.VISIBLE);
	}

	public void showLayoutInfo2(String position, Map_MyLocation s) {
		tv_name.setText(position + "." + s.getAddress());
		tv_distance.setText("时间" + s.getTime());
		tv_price_a.setText("经度：" + s.getLat() + " ");
		tv_price_b.setText("纬度：" + s.getLon() + " ");
		ll_summary.setVisibility(View.VISIBLE);
	}

	public void searchStation(double lat, double lon, int distance) {
		showLoadingDialog();
		mBaiduMap.clear();
		ll_summary.setVisibility(View.GONE);
		stationData.getStationData(lat, lon, distance);
	}

	/**
	 * 根据distance,获取当前位置附近的加油站
	 * 
	 * @param text
	 * @param distance
	 */
	public void distanceSearch(String text, int distance) {
		mDistance = distance;
		tv_title_right.setText(text);
		searchStation(loc.getLatitude(), loc.getLongitude(), distance);
		selectDialog.dismiss();
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			if (location == null) {
				return;
			}
			loc = location;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					.direction(location.getDirection())
					.latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			Log.e("test", "地图在自动刷新");
			/************************* 修改 ********/
			// searchStation(location.getLatitude(), location.getLongitude(),
			// mDistance);
			// 获取当前定位信息后应当保存于数据库中--me
			// addDB(location);
			// selectDB();
			myLocation = new Map_MyLocation();
			myLocation.setAddress("未定义");
			myLocation.setTime(MyTimeUtils.getTime());
			myLocation.setLon(location.getLongitude());
			myLocation.setLat(location.getLatitude());
			mylocList.add(myLocation);
			setMarker2(mylocList);

		}
	}

	/**
	 * dialog点击事件
	 * 
	 * @param v
	 *            点击的view
	 */
	public void onDialogClick(View v) {
		switch (v.getId()) {
		case R.id.bt_3km:
			distanceSearch("3km >", 3000);
			break;
		case R.id.bt_5km:
			distanceSearch("5km >", 5000);
			break;
		case R.id.bt_8km:
			distanceSearch("8km >", 8000);
			break;
		case R.id.bt_10km:
			distanceSearch("10km >", 10000);
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		// case R.id.iv_list:
		// Intent listintent = new Intent(mContext, StationListActivity.class);
		// listintent.putParcelableArrayListExtra("list", mList);
		// listintent.putExtra("locLat", loc.getLatitude());
		// listintent.putExtra("locLon", loc.getLongitude());
		// startActivity(listintent);
		// break;
		case R.id.iv_list:
			Intent listintent = new Intent(mContext,
					Map_StationListActivity.class);
			listintent.putParcelableArrayListExtra("list", mylocList);
			startActivity(listintent);
			break;
		case R.id.iv_loc:
			// 以下为请求刷新位置
			int r = mLocationClient.requestLocation();
			switch (r) {
			case 1:
				showToast("服务没有启动。");
				break;
			case 2:
				showToast("没有监听函数。");
				break;
			case 6:
				showToast("请求间隔过短。");
				break;

			default:
				break;
			}

			break;
		case R.id.tv_title_button:
			showSelectDialog();
			break;
		case R.id.ll_summary:
			Intent infoIntent = new Intent(mContext,
					Map_StationInfoActivity.class);
			infoIntent.putExtra("s", mStation);
			infoIntent.putExtra("locLat", loc.getLatitude());
			infoIntent.putExtra("locLon", loc.getLongitude());
			startActivity(infoIntent);
			break;
		default:
			break;
		}

	}

	public void addDB(BDLocation location) {
		ContentValues cv = new ContentValues();
		cv.put(Map_MyStationDB.LON, location.getLongitude());
		cv.put(Map_MyStationDB.LAT, location.getLatitude());
		cv.put(Map_MyStationDB.ADDRESS, "待实现");
		cv.put(Map_MyStationDB.TIME, MyTimeUtils.getTime() + "");
		dbWriter.insert(Map_MyStationDB.TABLE_NAME, null, cv);
	}

	public void selectDB() {
		Cursor cursor = dbReader.query(Map_MyStationDB.TABLE_NAME, null, null,
				null, null, null, null);
		while (cursor.moveToNext()) {
			double lon = cursor.getDouble(cursor
					.getColumnIndex(Map_MyStationDB.LON));
			double lat = cursor.getDouble(cursor
					.getColumnIndex(Map_MyStationDB.LAT));
			String address = cursor.getString(cursor
					.getColumnIndex(Map_MyStationDB.ADDRESS));
			String time = cursor.getString(cursor
					.getColumnIndex(Map_MyStationDB.TIME));
			Log.e("test", "数据库输出-->" + "lon=" + lon + " lat=" + lat
					+ "address:" + address + "time:" + time);
		}
	}

	/**
	 * 显示范围选择dialog
	 */
	@SuppressLint("InflateParams")
	private void showSelectDialog() {
		if (selectDialog != null) {
			selectDialog.show();
			return;
		}
		selectDialog = new Dialog(mContext, R.style.dialog);
		View view = LayoutInflater.from(mContext).inflate(
				R.layout.dialog_distance, null);
		selectDialog.setContentView(view, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
		selectDialog.setCanceledOnTouchOutside(true);
		selectDialog.show();
	}

	@SuppressLint("InflateParams")
	private void showLoadingDialog() {
		if (loadingDialog != null) {
			loadingDialog.show();
			return;
		}
		loadingDialog = new Dialog(mContext, R.style.dialog_loading);
		View view = LayoutInflater.from(mContext).inflate(
				R.layout.dialog_loading, null);
		loadingDialog.setContentView(view, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
		loadingDialog.setCancelable(false);
		loadingDialog.show();
	}

	/**
	 * 显示通知
	 * 
	 * @param msg
	 */
	private void showToast(String msg) {
		if (mToast == null) {
			mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
		}
		mToast.setText(msg);
		mToast.show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mMapView.onResume();
		mLocationClient.start();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mMapView.onPause();
		mLocationClient.stop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mMapView.onDestroy();
		mHandler = null;
		refreshing = false;
	}

}
